#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <cerrno>
#include "log.hpp"

//typedef std::function<std::string(const std::string&)> func_t;
using func_t = std::function<std::string(const std::string&)>;

Log lg;

enum{
    SOCKET_ERR = 1,
    BIND_ERR
};

uint16_t defaultport = 8080; // 默认端口号
std::string defaultip = "0.0.0.0"; // 默认ip
const int size = 1024;

class UdpServer
{
public:
    UdpServer(const uint16_t& port = defaultport, const std::string& ip = defaultip)
    :_sockfd(0), _port(port), _ip(ip), _isrunning(false)
    {}

    void Init()
    {
        // 创建udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); // AF_INET表示IPv4, SOCK_DGRAM表示UDP套接字, 0让系统自动选择对应协议
        if (_sockfd < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d", _sockfd);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success, sockfd: %d", _sockfd);
        // bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // 将local初始化为0
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); // htons将主机字节序转换为网络字节序(大端字节序)
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // inet_addr是把点分十进制ip地址字符串转换为网络字节序整数
    
        // 绑定套接字
        if (bind(_sockfd, (const struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void Run(func_t func)
    {
        _isrunning = true;
        char inbuffer[size];
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // udp通信接收数据
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
            if (n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            std::string info = inbuffer;
            std::string echo_string = func(info);
            // udp通信发送数据
            sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (const sockaddr*)&client, len);
        }
    }

    ~UdpServer()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }
private:
    int _sockfd; // 网络文件描述符
    std::string _ip; // 任意地址
    uint16_t _port; // 服务器进程的端口号
    bool _isrunning; // 判断服务器是否运行
};